<template>
  <div>
    <div>
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="120"
      >
        <FormItem label="商品名称" prop="storeName">
          <Input
            v-model="formValidate.storeName"
            placeholder="请输入商品名称"
          ></Input>
        </FormItem>
        <FormItem label="商品类型" prop="productSubTypeId">
          <Radio
            v-model="formValidate.productSubTypeId"
            :true-value="1"
            :false-value="0"
            >单品</Radio
          >
        </FormItem>
        <FormItem label="商品价格" prop="price">
          <Input
            v-model="formValidate.price"
            placeholder="请输入商品价格"
          ></Input>
        </FormItem>
        <FormItem label="备餐时间(分钟)" prop="prepareMeal">
          <Input
            v-model="formValidate.prepareMeal"
            placeholder="请输入"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="库存数量" prop="stock">
          <Input
            v-model="formValidate.stock"
            placeholder="请输入"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="商品分类" prop="productTypeId">
          <!-- <Cascader
            :data="cateList"
            :load-data="loadData"
            change-on-select
            @on-change="changeCate"
          ></Cascader> -->
          <Cascader
            :data="cateList"
            change-on-select
            @on-change="changeCate"
            v-model="productTypeId"
          ></Cascader>
        </FormItem>

        <FormItem label="排序" prop="sort">
          <Input
            v-model="formValidate.sort"
            placeholder="请输入商品排序"
            type="number"
          ></Input>
        </FormItem>
        <FormItem label="商品封面图（建议尺寸：188*188）" prop="image">
          <!-- <upload-pic-input v-model="formValidate.image"></upload-pic-input> -->
          <upload-pic-thumb v-model="formValidate.image"></upload-pic-thumb>
        </FormItem>
        <FormItem label="商品图轮播(建议尺寸:710*322)" prop="sliderImage1">
          <upload-pic-thumb
            v-model="formValidate.sliderImage1"
            multiple="true"
          ></upload-pic-thumb>
        </FormItem>
        <FormItem label="商品推荐" prop="isRecommand">
          <i-switch
            v-model="formValidate.isRecommand"
            :true-value="1"
            :false-value="0"
          >
            <span slot="open">on</span>
            <span slot="close">off</span>
          </i-switch>
        </FormItem>
        <FormItem label="商品状态">
          <div style="display: flex">
            <Checkbox
              label="火爆"
              :true-value="1"
              :false-value="0"
              v-model="formValidate.isHot"
            ></Checkbox>
            火爆
            <Checkbox
              style="margin-left: 5px"
              label="售罄"
              :true-value="1"
              v-model="formValidate.isSoldOut"
              :false-value="0"
            ></Checkbox
            >售罄
          </div>
        </FormItem>
        <FormItem label="产品描述，建议图片尺寸：500*300" prop="storeInfo">
          <!-- <Input
            v-model="formValidate.storeInfo"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder=""
          ></Input> -->

            <div class="cantainer">
              <div class="avatar-uploader">
                <Upload
                  :action="uploadFileUrl"
                  :headers="accessToken"
                  :on-success="handleSuccess"
                  :show-upload-list="false"
                >
                  <div id="Uploadfiles1"></div>
                </Upload>
              </div>
              <quill-editor
                class="editorCont"
                v-model="formValidate.storeInfo"
                ref="myQuillEditor"
                :options="editorOption"
              >
              </quill-editor>
            </div>
          </FormItem>
    
        <FormItem label="是否上架" prop="isShow">
          <i-switch
            v-model="formValidate.isShow"
            :true-value="1"
            :false-value="0"
          >
            <span slot="open">是</span>
            <span slot="close">否</span>
          </i-switch>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmit('formValidate')"
            >提交</Button
          >
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import uploadPicThumb from "@/views/my-components/xboot/upload-pic-thumb";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image", "video"], // 链接、图片、视频
];
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import {
  scProductTypegetByParentId,
  scProductAdd,
  getAllByCompanyId,
  scProductEdit,
  scProductGetDetailById,
  uploadFile,
} from "@/api/index";
export default {
  props: ["formData"],
  components: { uploadPicInput, uploadPicThumb, quillEditor },
  data() {
    return {
      accessToken: {},
      uploadFileUrl: uploadFile,
      editorOption: {
        placeholder: "请编辑相关内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              image: function (value) {
                if (value) {
                  document
                    .querySelector(".avatar-uploader #Uploadfiles1")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      productTypeId: [],
      selectCate: [],
      cateList: [],
      companyId: localStorage.getItem("companyId"),
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      formValidate: {
        isRecommand: 0,
        isHot: 0,
        isSoldOut: 0,
        productSubTypeId: 1,
        isShow: 1,
      },
      ruleValidate: {
        storeName: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        stock: [
          {
            required: true,
            message: "请输入商品库存",
            trigger: "blur",
          },
        ],
        prepareMeal: [
          {
            required: true,
            message: "请输入备餐时间",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: "请输入排序",
            trigger: "blur",
          },
        ],
        image: [
          {
            required: true,
            message: "请选择封面图",
            trigger: "blur",
          },
        ],
        sliderImage1: [
          {
            required: true,
            message: "请选择轮播图",
            trigger: "blur",
            type: "array",
          },
        ],
        isRecommand: [
          {
            required: true,
            message: "推荐",
            trigger: "change",
            type: "number",
          },
        ],
        productSubTypeId: [
          {
            required: true,
            message: "商品类型",
            trigger: "change",
            type: "number",
          },
        ],
        productTypeId: [
          {
            required: true,
            message: "请选择分类",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
     this.accessToken = {
      accessToken: this.getStore("accessToken"),
    };
    if (this.formData.id) {
      scProductGetDetailById(this.formData).then((res) => {
        console.log("res1", res);
        this.formValidate = {
          ...res.result,
          price: String(this.formData.price),
          sort: String(this.formData.sort),
          stock: String(this.formData.stock),
          prepareMeal: String(this.formData.prepareMeal),
        };
        this.productTypeId = [res.result.productTypeId];
        this.formValidate.sliderImage1 = res.result.sliderImage.split(",");
      });
    }

    this.initgetCateList(0);
  },
  methods: {
     handleSuccess(res, file) {
      this.loading = false;
      if (res.success) {
        this.uploadSuccess(res.result);
      } else {
        this.$Message.error(res.message);
      }
    },
    uploadSuccess(res, fileUpDom) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      var _this = this;
      let quill = _this.$refs.myQuillEditor.quill;
      // 获取光标所在位置
      let length = 0;
      let Selection = quill.getSelection();
      if (Selection && Selection.index) {
        length = Selection.index;
      }
      // 如果上传成功
      console.log("res:", res);
      quill.insertEmbed(length, "image", res);
      quill.setSelection(length + 1);
     
    },
    handleSubmit(name) {
      console.log(this.formValidate);
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.formValidate.sliderImage =
            this.formValidate.sliderImage1.join(",");
          if (this.formValidate.id) {
            let data = this.formValidate;
            if (!data.homePageDate) {
              delete data.homePageDate;
            }
            if (!data.openStartDate) {
              delete data.openStartDate;
            }
            if (!data.openEndDate) {
              delete data.openEndDate;
            }
            if (!data.courseFeature) {
              delete data.courseFeature;
            }
            if (!data.prepareMeal) {
              delete data.prepareMeal;
            }
            if (!data.status && data.status !== false && data.status !== 0) {
              delete data.status;
            }
            if (!data.courseNames) {
              delete data.courseNames;
            }
            if (!data.subNumber) {
              delete data.subNumber;
            }
            if (!data.vipCardIds) {
              delete data.vipCardIds;
            }
            if (!data.validDay) {
              delete data.validDay;
            }
            if (!data.soldierType) {
              delete data.soldierType;
            }
            if (!data.classStartDate) {
              delete data.classStartDate;
            }
            if (!data.classEndDate) {
              delete data.classEndDate;
            }
            scProductEdit({
              ...data,
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$emit("handleSubmit", true);
              }
            });
          } else {
            scProductAdd({
              ...this.formValidate,
              companyId: this.companyId,
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$emit("handleSubmit", true);
              }
            });
          }
        } else {
          //   this.$Message.error("Fail!");
        }
      });
    },
    changeCate(e) {
      console.log(e);
      this.selectCate = e;
      this.formValidate.productTypeId = e[e.length - 1];
    },
    listFormat(list) {
      let tmp = [];
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        console.log(item);
        // 无children
        if (item.children.length == 0) {
          tmp.push({
            value: item.id,
            label: item.title,
          });
          // 有children
        } else {
          tmp.push({
            value: item.id,
            label: item.title,
            children: this.listFormat(item.children),
          });
        }
      }
      return tmp;
    },
    initgetCateList(parentId) {
      getAllByCompanyId({ companyId: this.companyId }).then((res) => {
        console.log(res);
        this.cateList = this.listFormat(res.result);
      });
      return;
      scProductTypegetByParentId({
        companyId: this.companyId,
        parentId: parentId,
      }).then((res) => {
        console.log("懒加载");
        if (res.code == 200) {
          let data = res.result.map((item) => {
            item.label = item.title;
            item.value = item.id;
            if (item.isParent) {
              item.children = [];
              item.loading = false;
            }
            return item;
          });
          this.cateList = data;
        }
      });
    },
    loadData(item0, callback) {
      item0.loading = true;
      scProductTypegetByParentId({
        companyId: this.companyId,
        parentId: item0.id,
      }).then((res) => {
        console.log("懒加载");
        if (res.code == 200) {
          let data = res.result.map((item) => {
            item.label = item.title;
            item.value = item.id;
            if (item.isParent) {
              item.children = [];
              item.loading = false;
            }
            return item;
          });
          item0.children = data;
          item0.loading = false;
          callback();
        }
      });
    },
  },
};
</script>

<style>
</style>